package services

import (
	"context"
	"crypto/ecdsa"
	"log"
	"math/big"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/ethclient"
)

type EthClient struct {
	Client     *ethclient.Client
	PrivateKey *ecdsa.PrivateKey
	PublicKey  *ecdsa.PublicKey
	Address    common.Address
	ChainID    *big.Int
}

// NewEthClient 初始化客户端
func NewEthClient(rpcURL, privateKeyHex string) (*EthClient, error) {
	// 连接到以太坊节点
	client, err := ethclient.Dial(rpcURL)
	if err != nil {
		return nil, err
	}

	// 加载私钥
	privateKey, err := crypto.HexToECDSA(privateKeyHex)
	if err != nil {
		return nil, err
	}

	publicKey := privateKey.Public()
	publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
	if !ok {
		log.Fatal("无法获取公钥")
	}

	address := crypto.PubkeyToAddress(*publicKeyECDSA)

	// 获取 ChainID
	chainID, err := client.ChainID(context.Background())
	if err != nil {
		return nil, err
	}

	return &EthClient{
		Client:     client,
		PrivateKey: privateKey,
		PublicKey:  publicKeyECDSA,
		Address:    address,
		ChainID:    chainID,
	}, nil
}
